package com.protocol;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @Author linyu.dai
 * @Description TODO
 * @Date 2022/11/24 11:45
 */
public interface Serializer {

    /**
     * @Author linyu.dai
     * @Description 反序列化
     * @Date 2022/11/24 11:37
     * @Param [clazz, bytes]
     * @return T
     */
    <T> T deserialize(Class<T> clazz, byte[] bytes);

    /**
     * @Author linyu.dai
     * @Description 序列化
     * @Date 2022/11/24 11:37
     * @Param [object]
     * @return byte[]
     */
    <T> byte[] serializer(T object);

    ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    @Slf4j
    enum Algorithm implements Serializer{

        //JDK序列化方式
        JDK{
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                try {
                    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
                    return  (T) ois.readObject();

                }catch (IOException | ClassNotFoundException e) {
                    throw new RuntimeException("序列化失败",e);
                }
            }

            @Override
            public <T> byte[] serializer(T object) {
                try {
                  ByteArrayOutputStream bos = new ByteArrayOutputStream();
                  ObjectOutputStream oos = new ObjectOutputStream(bos);
                  oos.writeObject(object);
                    return bos.toByteArray();
                } catch (IOException e) {
                    throw new RuntimeException("序列化失败",e);

                }
            }
        },

        //JSON序列化方式
        JSON{
            @Override
            public <T> T deserialize(Class<T> clazz, byte[] bytes) {
                try {
                   return objectMapper.readValue(bytes, clazz);
                } catch (IOException e) {
                    log.error("json 反序列化异常{}",e.getMessage());
                }
                return null;
            }

            @Override
            public <T> byte[] serializer(T object) {
                try {
                    return  objectMapper.writeValueAsBytes(object);
                } catch (JsonProcessingException e) {
                    log.error("json 序列化异常{}",e.getMessage());
                }
                return null;
            }

        }
    }
}
